using System;
using System.IO;

namespace Sunny.UI;

public static class Dir
{
	public static bool CreateDir(string dir)
	{
		if (dir.IsNullOrEmpty())
		{
			throw new ArgumentNullException(dir, "目录不能为空。");
		}
		if (!Path.IsPathRooted(dir))
		{
			throw new ArgumentException(dir, "不包含根路径。");
		}
		try
		{
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
			return Directory.Exists(dir);
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
			return false;
		}
	}

	public static string CurrentDir()
	{
		return AppDomain.CurrentDomain.BaseDirectory.DealPath();
	}

	public static string TempPath()
	{
		return Path.GetTempPath().DealPath();
	}

	public static string TempRandomPath()
	{
		string dir = TempPath() + RandomEx.RandomPureChar(16);
		Directory.CreateDirectory(dir.DealPath());
		return dir.DealPath();
	}

	public static bool TryDelete(string dir)
	{
		try
		{
			Directory.Delete(dir);
			return !Directory.Exists(dir);
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message);
			return false;
		}
	}

	public static string YearMonthDayFolder(this DateTime dt, string dir, bool createIfNotExist = true, bool withLink = true)
	{
		if (dir.IsNullOrEmpty())
		{
			throw new ArgumentNullException(dir, "目录不能为空。");
		}
		if (!Path.IsPathRooted(dir))
		{
			throw new ArgumentException(dir, "不包含根路径。");
		}
		string dir2 = dir.DealPath() + dt.YearString();
		dir2 = dir2.DealPath() + dt.YearMonthString(withLink);
		dir2 = dir2.DealPath() + dt.DateString(withLink);
		dir2 = dir2.DealPath();
		if (createIfNotExist)
		{
			CreateDir(dir2);
		}
		return dir2;
	}

	public static string YearMonthFolder(this DateTime dt, string dir, bool createIfNotExist = false, bool withLink = true)
	{
		if (dir.IsNullOrEmpty())
		{
			throw new ArgumentNullException(dir, "目录不能为空。");
		}
		if (!Path.IsPathRooted(dir))
		{
			throw new ArgumentException(dir, "不包含根路径。");
		}
		string dir2 = dir.DealPath() + dt.YearString();
		dir2 = dir2.DealPath() + dt.YearMonthString(withLink);
		dir2 = dir2.DealPath();
		if (createIfNotExist)
		{
			CreateDir(dir2);
		}
		return dir2;
	}

	public static void Copy(string sourceDir, string destDir)
	{
		Copy(new DirectoryInfo(sourceDir), new DirectoryInfo(destDir));
	}

	public static void Copy(DirectoryInfo source, DirectoryInfo dest)
	{
		if (dest.FullName.StartsWith(source.FullName, StringComparison.CurrentCultureIgnoreCase))
		{
			throw new Exception("父目录不能拷贝到子目录！");
		}
		if (source.Exists)
		{
			if (!dest.Exists)
			{
				dest.Create();
			}
			FileInfo[] files = source.GetFiles();
			foreach (FileInfo fileInfo in files)
			{
				File.Copy(fileInfo.FullName, Path.Combine(dest.FullName, fileInfo.Name), overwrite: true);
			}
			DirectoryInfo[] directories = source.GetDirectories();
			foreach (DirectoryInfo directoryInfo in directories)
			{
				Copy(directoryInfo.FullName, Path.Combine(dest.FullName, directoryInfo.Name));
			}
		}
	}
}
